package com.edu.dao.impl;

import com.edu.dao.BaseDao;
import com.edu.dao.RentalsDao;
import com.edu.entity.Rentals;
import com.edu.entity.User;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

public class RentalsDaoImpl extends BaseDao implements RentalsDao {
    @Override
    public List<Rentals> getUidRentals(int id) {
        String sql = "SELECT rentals.id, vehicles.type, vehicles.name, rentals.rental_time, rentals.duration, rentals.total_cost, rentals.state\n" +
                "FROM rentals \n" +
                "INNER JOIN vehicles ON rentals.vehicle_id = vehicles.id \n" +
                "WHERE user_id = " + id;
        System.out.println(sql);
        ResultSet resultSet = super.queryResultSet(sql);
        List<Rentals> list = new ArrayList<Rentals>();
        try {
            while (resultSet.next()) {
                int id1 = resultSet.getInt("id");
                String type = resultSet.getString("type");
                String name = resultSet.getString("name");
                LocalDateTime rentalTiem = resultSet.getTimestamp("rental_time").toLocalDateTime();
                int duration = resultSet.getInt("duration");
                Double totalCost = resultSet.getDouble("total_cost");
                int state = resultSet.getInt("state");
                list.add(new Rentals(id1, type, name, rentalTiem, duration, totalCost, state));
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            super.closeAll(conn, ps, resultSet);
        }
        return list;
    }

    @Override
    public int addRental(int uId, int vId, int duration, double totalCost) {
        String sql = "INSERT INTO rentals (user_id, vehicle_id, rental_time, duration, total_cost,state) VALUES\n" +
                "(?, ?, now(), ?, ?,0)";
        Object[] arr = {uId, vId, duration, totalCost};
        return BaseDao.executeUpdate(sql,arr);
    }
}
